package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.BaseColorInfo;

/**
 * 配置页面，分为两个板块，套装，车配置
 * 
 * @author apple
 * 
 */
public class ConfigurationActivity extends BaseActivity {

	private Button rightButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.config_info);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		this.settingTitle(R.id.title, "设定配置");
		showBackButton();

		list1 = (ListView) findViewById(R.id.list1);

		list1.setOnItemClickListener(list1ItemClickListener);
		list2 = (ListView) findViewById(R.id.list2);
		list2.setOnItemClickListener(list2ItemClickListener);

		list3 = (ListView) findViewById(R.id.list3);

		list3.setOnItemClickListener(list3ItemClickListener);

		list4 = (ListView) findViewById(R.id.list4);
		list4.setOnItemClickListener(list4ItemClickListener);
		rightButton = (Button) findViewById(R.id.rightButton);

		this.rightButton.setVisibility(View.VISIBLE);
		this.rightButton.setText("保存");
		this.rightButton.setOnClickListener(completeListener);
		utils = NetworkProgressUtils.getInstance();

		Intent intent = getIntent();
		cId = intent.getStringExtra("cId");
		System.out.println("cId=====" + cId);
		isEditor = intent.getBooleanExtra("isEditor", false);
		HashMap<String, ArrayList<BaseColorInfo>> allItems = mApp
				.getAllConfigurations();

		if (allItems.size() == 0) {
			new ConfigurationTask(KEY1,
					ConstantUtils.GET_SUIT_BY_SERIES_ID_URL, list1)
					.execute(cId);

			new ConfigurationTask(KEY2,
					ConstantUtils.GET_CONFIGURATION_BY_SERIES_ID_URL, list2)
					.execute(cId);

			new ConfigurationTask(KEY3,
					ConstantUtils.GET_CONFIGURATION_GXH_BY_SERIES_ID_URL, list3)
					.execute(cId);

			new ConfigurationTask(KEY4,
					ConstantUtils.GET_CONFIGURATION_LM_BY_SERIES_ID_URL, list4)
					.execute(cId);
		} else {

			// System.out.println("start====>");
			ArrayList<BaseColorInfo> bc1 = allItems.get(KEY1);
			ArrayList<BaseColorInfo> bc2 = allItems.get(KEY2);

			ArrayList<BaseColorInfo> bc3 = allItems.get(KEY3);
			ArrayList<BaseColorInfo> bc4 = allItems.get(KEY4);

			ArrayList<String> allItems1 = new ArrayList<String>();
			ArrayList<String> allItems2 = new ArrayList<String>();

			ArrayList<String> allItems3 = new ArrayList<String>();
			ArrayList<String> allItems4 = new ArrayList<String>();
			for (int i = 0; i < bc1.size(); i++) {

				BaseColorInfo b = bc1.get(i);
				allItems1.add(b.getDdname());
			}

			for (int i = 0; i < bc2.size(); i++) {

				BaseColorInfo b = bc2.get(i);
				allItems2.add(b.getDdname());
			}

			for (int i = 0; i < bc3.size(); i++) {

				BaseColorInfo b = bc3.get(i);
				allItems3.add(b.getDdname());
			}

			for (int i = 0; i < bc4.size(); i++) {

				BaseColorInfo b = bc4.get(i);
				allItems4.add(b.getDdname());
			}

			MyConfigurationAdapter adapter1 = new MyConfigurationAdapter(
					allItems1);
			list1.setAdapter(adapter1);
			list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			MyConfigurationAdapter adapter2 = new MyConfigurationAdapter(
					allItems2);
			list2.setAdapter(adapter2);
			list2.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

			MyConfigurationAdapter adapter3 = new MyConfigurationAdapter(
					allItems3);
			list3.setAdapter(adapter3);
			list3.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			MyConfigurationAdapter adapter4 = new MyConfigurationAdapter(
					allItems4);
			list4.setAdapter(adapter4);
			list4.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

			long[] c1Ids = mApp.getConfigurationOneIds();
			long[] c2Ids = mApp.getConfigurationTwoIds();

			long[] c3Ids = mApp.getConfigurationThreeIds();
			long[] c4Ids = mApp.getConfigurationFourIds();

			if (c1Ids != null) {
				this.mCheckOneIds = c1Ids;
				for (int i = 0; i < c1Ids.length; i++) {

					list1.setItemChecked((int) c1Ids[i], true);

				}
				adapter1.notifyDataSetChanged();

			}

			if (c2Ids != null) {
				this.mCheckTwoIds = c2Ids;
				for (int i = 0; i < c2Ids.length; i++) {
					list2.setItemChecked((int) c2Ids[i], true);

				}
				adapter2.notifyDataSetChanged();
			}

			if (c3Ids != null) {
				this.mCheckThreeIds = c3Ids;
				for (int i = 0; i < c3Ids.length; i++) {
					list3.setItemChecked((int) c3Ids[i], true);

				}
				adapter3.notifyDataSetChanged();
			}

			if (c4Ids != null) {
				this.mCheckFourIds = c4Ids;
				for (int i = 0; i < c4Ids.length; i++) {
					list4.setItemChecked((int) c4Ids[i], true);

				}
				adapter4.notifyDataSetChanged();
			}
			//
			// System.out.println("long1==" + c1Ids.length + ",long2=="
			// + c2Ids.length);
		}

	}

	public static final String KEY1 = "20";
	public static final String KEY2 = "16";
	public static final String KEY3 = "43";
	public static final String KEY4 = "44";
	private String cId;
	private ListView list1;
	private ListView list2;
	private ListView list3;
	private ListView list4;
	private long[] mCheckOneIds;
	private long[] mCheckTwoIds;
	private long[] mCheckThreeIds;
	private long[] mCheckFourIds;
	private boolean isEditor;
	private NetworkProgressUtils utils;

	private OnClickListener completeListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			if (mCheckOneIds ==null
					&& mCheckTwoIds == null
					&&mCheckThreeIds == null
					&& mCheckFourIds == null
					) {
				Toast.makeText(ConfigurationActivity.this, "亲，没有设定配置哟^＆^",
						Toast.LENGTH_SHORT).show();
				
				mApp.setSelect(false);
			} else {

				mApp.setConfigurationOneIds(mCheckOneIds);
				mApp.setConfigurationTwoIds(mCheckTwoIds);
				mApp.setConfigurationThreeIds(mCheckThreeIds);
				mApp.setConfigurationFourIds(mCheckFourIds);
				//finish();
				mApp.setSelect(true);
			}
			finish();
			// HashMap<String, ArrayList<String>> all = mApp
			// .getAllConfigurations();
			// // System.out.println(all.size());
			//
			// Set s = all.entrySet();
			// Iterator i = s.iterator();
			// while (i.hasNext()) {
			// Entry e = (Entry) i.next();
			//
			// System.out.println(e.getKey() + "..." + e.getValue());
			// }
		}
	};

	private OnItemClickListener list1ItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			// mApp.setConfigurationOneIds(list1.getCheckItemIds());
			mCheckOneIds = list1.getCheckItemIds();
			// mCheckIds = list1.getCheckItemIds();

			// System.out.println(view);
			// System.out.println(view.findViewById(android.R.id.toggle));
			// System.out.println(l);

		}
	};

	// private long[] mCheckIds;
	private OnItemClickListener list2ItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			// mApp.setConfigurationTwoIds(list2.getCheckItemIds());
			mCheckTwoIds = list2.getCheckItemIds();
		}
	};

	private OnItemClickListener list3ItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			// mApp.setConfigurationOneIds(list1.getCheckItemIds());
			mCheckThreeIds = list3.getCheckItemIds();
			// mCheckIds = list1.getCheckItemIds();

			// System.out.println(view);
			// System.out.println(view.findViewById(android.R.id.toggle));
			// System.out.println(l);

		}
	};

	private OnItemClickListener list4ItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			// mApp.setConfigurationOneIds(list1.getCheckItemIds());
			mCheckFourIds = list4.getCheckItemIds();
			// mCheckIds = list1.getCheckItemIds();

			// System.out.println(view);
			// System.out.println(view.findViewById(android.R.id.toggle));
			// System.out.println(l);

		}
	};

	private class ConfigurationTask extends
			AsyncTask<String, String, ArrayList<BaseColorInfo>> {

		public ConfigurationTask(String methodId, String requestURL,
				ListView list) {
			this.methodId = methodId;
			this.requestURL = requestURL;
			this.list = list;
		}

		private String methodId;
		private String requestURL;
		private ListView list;

		@Override
		protected ArrayList<BaseColorInfo> doInBackground(String... params) {

			HashMap<String, String> allParams = new HashMap<String, String>();
			allParams.put("seriesId", params[0]);
			// 20/16
			Object o = utils
					.getWebservicesByData(
							ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(Integer
									.parseInt(methodId)),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME
											.get(Integer.parseInt(methodId)),
							requestURL, allParams);
			// System.out.println(o);
			ArrayList<BaseColorInfo> all = utils.parseJsonColor(o.toString(),
					"table", false);

			return all;
		}

		@Override
		protected void onPostExecute(ArrayList<BaseColorInfo> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			ArrayList<String> all = null;
			if (result != null) {

				all = new ArrayList<String>();
				ArrayList<String> allIds = new ArrayList<String>();

				for (BaseColorInfo b : result) {

					all.add(b.getDdname());
					allIds.add(b.getId());
				}
				mApp.getAllConfigurations().put("" + methodId, result);

				MyConfigurationAdapter adapter = new MyConfigurationAdapter(all);

				// ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				// getApplicationContext(),
				// // android.R.layout.simple_list_item_multiple_choice,
				// android.R.id.text1, all);
				list.setAdapter(adapter);
				list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				ArrayList<Long> tmps = new ArrayList<Long>();
				if (isEditor) {
					mApp.setUpdateConfigState(true);
					String allConfs = mApp.getmEditCarInfo().getDdid();
					String[] allConfIds = allConfs.split(",");

					for (String string : allConfIds) {
						// System.out.println("---ddid--"+string);
						int index = allIds.indexOf(string);
						if (index != -1) {
							list.setItemChecked(index, true);
							tmps.add(Long.valueOf(index));

						}

					}
					if (methodId.equals(KEY1)) {
						long[] saves = progressEles(tmps, tmps.size());
						// System.out.println(mCheckOneIds);
						mCheckOneIds = saves;
						mApp.setConfigurationOneIds(saves);
					} else if (methodId.equals(KEY2)) {
						long[] saves = progressEles(tmps, tmps.size());
						mCheckTwoIds = saves;
						mApp.setConfigurationTwoIds(saves);
					} else if (methodId.equals(KEY3)) {
						long[] saves = progressEles(tmps, tmps.size());
						mCheckThreeIds = saves;
						mApp.setConfigurationThreeIds(saves);
					} else if (methodId.equals(KEY4)) {
						long[] saves = progressEles(tmps, tmps.size());
						mCheckFourIds = saves;
						mApp.setConfigurationFourIds(saves);
					}

					adapter.notifyDataSetChanged();
					// /String

				}
			}
		}
	}

	private class MyConfigurationAdapter extends BaseAdapter {

		private List<String> listDatas;

		public MyConfigurationAdapter(List<String> listDatas) {
			this.listDatas = listDatas;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listDatas.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listDatas.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = LayoutInflater.from(getApplicationContext()).inflate(
					android.R.layout.simple_list_item_multiple_choice, null);
			TextView tv = (TextView) convertView
					.findViewById(android.R.id.text1);
			tv.setTextColor(getBaseContext().getResources().getColor(
					R.color.blue_config));
			tv.setText(listDatas.get(position));
			return convertView;
		}

	}

	// 处理编辑配置显示的元素值
	private long[] progressEles(ArrayList arrays, int size) {

		Iterator i = arrays.iterator();
		long[] saves = new long[size];
		int index = 0;
		while (i.hasNext()) {
			saves[index] = Long.parseLong(i.next().toString());
			System.out.println("-----@@@@@@" + saves[index]);
			index++;

		}
		return saves;
	}
}
